<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类的ID" prop="categoryId">
        <el-input
          v-model="queryParams.categoryId"
          placeholder="请输入分类的ID"
          clearable
          @keyup.enter.native="handleQuery"
          :disabled="single"
        />
      </el-form-item>
      <el-form-item label="作品标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入作品标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="作品状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择作品状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.ai_work_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ai:work:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ai:work:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ai:work:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ai:work:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="workList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="作品ID" align="center" prop="workId" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="分类的ID" align="center" prop="categoryId" />
      <el-table-column label="作品标题" align="center" prop="title" />
      <el-table-column label="图片地址" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="使用人数" align="center" prop="userNumber" />
      <el-table-column label="点赞数" align="center" prop="likeNumber" />
      <el-table-column label="收藏数" align="center" prop="collectNumber" />
      <el-table-column label="对话次数" align="center" prop="chatNumber" />
      <el-table-column label="作品的内容" align="center" prop="content" />
      <el-table-column label="作品状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.ai_work_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-star-on"
            @click="handleUpdatelike(scope.row)"
            v-hasPermi="['ai:like:update']"
            >点赞</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ai:work:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ai:work:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改作品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" :disabled="true"/>
        </el-form-item>
        <el-form-item label="作品分类" prop="categoryId">
          <treeselect
            v-model="form.categoryId"
            :options="categoryOptions"
            :normalizer="normalizer"
            placeholder="请选择作品分类"
          />
        </el-form-item>
        <el-form-item label="作品标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入作品标题" />
        </el-form-item>
        <el-form-item label="图片地址" prop="image">
          <image-upload v-model="form.image" />
        </el-form-item>
        <el-form-item label="作品内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            placeholder="请输入作品内容"
          />
          <!-- <editor v-model="form.content" :min-height="192" /> -->
        </el-form-item>
        <el-form-item label="作品状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.ai_work_status"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="作品描述" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCategory,
  getCategory,
  delCategory,
  addCategory,
  updateCategory,
} from "@/api/ai/category";
import store from "@/store";
import { listWork, getWork, delWork, addWork, updateWork,updateLike } from "@/api/ai/work";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { number } from "echarts";
export default {
  name: "Work",
  dicts: ["ai_work_status"],
  components: {
    Treeselect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 分类树选项
      categoryOptions: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 作品管理表格数据
      workList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        quarantine:true,
        userId: null,
        categoryId: null,
        title: null,
        status: null,
        createTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "作品标题不能为空", trigger: "blur" },
        ],
        content: [
          { required: true, message: "作品内容不能为空", trigger: "blur" },
        ],
        status: [
          { required: true, message: "作品状态不能为空", trigger: "change" },
        ],
      },
      categoryId:undefined,
      userId:store.state.user.id//将缓存的用户id赋值给userId
    };
  },
  created() {
    this.categoryId=this.$route.params && this.$route.params.categoryId;
    if(this.categoryId){
      this.single=true
    }else{
      this.single=false
    }
    this.getList();
  },
  methods: {
    /** 转换分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.categoryId,
        label: node.categoryName,
        children: node.children,
      };
    },
    /** 查询分类下拉树结构 */
    getTreeselect() {
      listCategory().then((response) => {
        this.categoryOptions = [];
        const data = { categoryId: 0, categoryName: "顶级节点", children: [] };
        data.children = this.handleTree(
          response.data,
          "categoryId",
          "parentCategoryId"
        );
        this.categoryOptions.push(data);
      });
    },
    /** 查询作品管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && "" != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] =
          this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      if(this.categoryId){
        this.queryParams.categoryId=this.categoryId
      }
      
      listWork(this.queryParams).then((response) => {
        this.workList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        workId: null,
        userId: null,
        categoryId: null,
        title: null,
        image: null,
        userNumber: null,
        likeNumber: null,
        collectNumber: null,
        chatNumber: null,
        content: null,
        delFlag: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.workId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeselect();
      this.open = true;
      this.title = "添加作品管理";
      this.single=false
      this.form.userId=this.userId
      if(this.categoryId){
        this.single=true
        this.form.categoryId =this.categoryId
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      this.single=false
      const workId = row.workId || this.ids;
      getWork(workId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改作品管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.workId != null) {
            updateWork(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWork(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const workIds = row.workId || this.ids;
      this.$modal
        .confirm('是否确认删除作品管理编号为"' + workIds + '"的数据项？')
        .then(function () {
          return delWork(workIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    handleUpdatelike(row){
      const workId = row.workId
      this.$modal
        .confirm('是否点赞作品"' + row.title + '"？')
        .then(function () {
          return updateLike({workId: workId, number:1});
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("点赞"+ row.title +"成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "ai/work/export",
        {
          ...this.queryParams,
        },
        `work_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
